//
//  BBuyNowShopDetailImageCycleView.m
//  DistributorAB
//
//  Created by LZY on 2019/10/9.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "BBuyNowShopDetailImageCycleView.h"
@interface BBuyNowShopDetailImageCycleView ()<UIScrollViewDelegate>
{
    CGFloat preOffsetX;//手动拖拽时保存当前的偏移量，便于判断方向
}
@property (nonatomic, strong) UIScrollView *scrollView;//主滑动控件
@property (nonatomic, strong) UILabel *lblNumber;//分页控件
@property (nonatomic, strong) NSTimer *timer;//定时器
@property (nonatomic, assign) NSInteger currentPage;//当前页数
@property (nonatomic, assign) NSInteger pageCount;//页数
@property (nonatomic, assign) CGFloat timerFloat;//定时器间隔
@end

@implementation BBuyNowShopDetailImageCycleView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame withTimerValue:(CGFloat)timerValue{
    self = [super initWithFrame:frame];
    if (self) {
        self.timerFloat = timerValue;
        //启动定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timerFloat target:self selector:@selector(changePageRightAction) userInfo:nil repeats:YES];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    
    //添加滚动控件和分页控件
    [self addSubview:self.scrollView];
    [self addSubview:self.lblNumber];
    //设置初始页面
    self.scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
    self.currentPage = 1;
    
    [self updatePageContent];
}
- (void)reloadData{
    
    [self.scrollView removeFromSuperview];
    self.scrollView = nil;
    [self.lblNumber removeFromSuperview];
    self.lblNumber = nil;
    
    //添加滚动控件和分页控件
    [self addSubview:self.scrollView];
    [self addSubview:self.lblNumber];
    
    //设置初始页面
    self.scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
    self.currentPage = 1;
    
    [self updatePageContent];
    
    if (self.pageCount > 1) {
        if (!self.timer) {
            //启动定时器
            self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timerFloat target:self selector:@selector(changePageRightAction) userInfo:nil repeats:YES];
        }
        self.scrollView.scrollEnabled = YES;
    }else{
        //取消轮播
        [self.timer invalidate];
        self.timer = nil;
        self.scrollView.scrollEnabled = NO;
    }
    
}
#pragma mark -- 图片点击事件
- (void)pageCliked{
    // 当点击轮播图的时候
    if (self.delegate && [self.delegate respondsToSelector:@selector(cycleView:didSelectedAtIndex:)]){
        [self.delegate cycleView:self didSelectedAtIndex:_currentPage];
    }
}
#pragma mark -- UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    // 记录偏移量
    preOffsetX = scrollView.contentOffset.x;
    // 开始手动滑动时暂停定时器
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    // 左右边界
    CGFloat leftEdgeOffsetX = 0;
    CGFloat rightEdgeOffsetX = self.frame.size.width * (_pageCount + 1);
    
    if (scrollView.contentOffset.x < preOffsetX){
        // 左滑
        if (scrollView.contentOffset.x > leftEdgeOffsetX){
            self.currentPage = scrollView.contentOffset.x / self.frame.size.width;
        }else if (scrollView.contentOffset.x == leftEdgeOffsetX){
            self.currentPage = _pageCount;
        }
        
        if (scrollView.contentOffset.x == leftEdgeOffsetX){
            self.scrollView.contentOffset = CGPointMake(self.frame.size.width * _pageCount, 0);
        }
    }else{
        //右滑
        //设置小点
        if (scrollView.contentOffset.x < rightEdgeOffsetX){
            self.currentPage = scrollView.contentOffset.x / self.frame.size.width;
        }else if (scrollView.contentOffset.x == rightEdgeOffsetX){
            self.currentPage = 1;
        }
        
        //滑动完了之后从最后多余页赶紧切换到第一页
        if (scrollView.contentOffset.x == rightEdgeOffsetX){
            self.scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
        }
        
    }
    //结束后又开启定时器
    [self.timer setFireDate:[NSDate dateWithTimeInterval:self.timerFloat sinceDate:[NSDate date]]];
    
    [self updatePageContent];
    
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
}
#pragma mark - 定时器控制的滑动
//从右往左滑动
- (void)changePageRightAction{
    // 设置当前需要偏移的量，每次递增一个page宽度
    CGFloat offsetX = _scrollView.contentOffset.x + CGRectGetWidth(self.frame);
    
    // 根据情况进行偏移
    CGFloat edgeOffsetX = self.frame.size.width * (_pageCount + 1);  // 最后一个多余页面右边缘偏移量
    
    //从多余页往右边滑，赶紧先设置为第一页的位置
    if (offsetX > edgeOffsetX){
        //偏移量，不带动画，欺骗视觉
        self.scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
        //这里提前改变下一个要滑动到的位置为第二页
        offsetX = self.frame.size.width * 2;
    }
    
    //带动画滑动到下一页面
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    if (offsetX < edgeOffsetX){
        self.currentPage = offsetX / self.frame.size.width;
    }else if (offsetX == edgeOffsetX){
        //最后的多余那一页滑过去之后设置小点为第一个
        self.currentPage = 1;
    }
    
    [self updatePageContent];
    
}

//从左往右滑动
- (void)changePageLeftAction{
    // 设置当前需要偏移的量，每次递减一个page宽度
    CGFloat offsetX = _scrollView.contentOffset.x - CGRectGetWidth(self.frame);
    
    // 根据情况进行偏移
    CGFloat edgeOffsetX = 0;  // 最后一个多余页面左边缘偏移量
    
    // 从多余页往左边滑动，先设置为最后一页
    if (offsetX < edgeOffsetX){
        self.scrollView.contentOffset = CGPointMake(self.frame.size.width * _pageCount, 0);
        offsetX = self.frame.size.width * (_pageCount - 1);
    }
    
    // 带动画滑动到前一页面
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    if (offsetX > edgeOffsetX){
        self.currentPage = offsetX / self.frame.size.width;
    }else if (offsetX == edgeOffsetX){
        // 最后的多余那一页滑过去之后设置小点为最后一个
        self.currentPage = _pageCount;
    }
    
    
    [self updatePageContent];
}
#pragma mark - 更新分页内容
- (void)updatePageContent{
    self.lblNumber.text = [NSString stringWithFormat:@"%ld/%ld",self.currentPage,self.pageCount];
}
#pragma mark -- 懒加载
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        // 初始化尺寸
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        // 设置分页效果
        _scrollView.pagingEnabled = YES;
        // 水平滚动条隐藏
        _scrollView.showsHorizontalScrollIndicator = NO;
        // 设置到边的弹性隐藏
        _scrollView.bounces = NO;
        // 设置分页数
        self.pageCount = [self.dataSource numberOfImagesForView:self];
        // 设置滚动范围
        _scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.frame) * (_pageCount + 2), CGRectGetHeight(self.frame));
        // 设置代理
        _scrollView.delegate = self;
        
        // 添加分页，左右增加一页
        for (int i = 0; i < _pageCount + 2; i++){
            // 添加control,设置偏移位置
            UIControl *control = [[UIControl alloc] initWithFrame:CGRectMake(self.frame.size.width * i, 0, self.frame.size.width, self.frame.size.height)];
            UIView *pageView = nil;
            if (i == 0){
                // 第一页多余页跟最后一页一样并重新定义
                pageView = [self.dataSource cycleView:self imageAtIndex:_pageCount - 1];
            }else if (i == _pageCount + 1){
                // 最后多余的一页跟第一页一样并重新定义
                pageView = [self.dataSource cycleView:self imageAtIndex:0];
            }else{
                pageView = [self.dataSource cycleView:self imageAtIndex:i - 1];
            }
            // 添加pageview
            pageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
            //pageView.layer.cornerRadius = 10.0;
            //pageView.layer.masksToBounds = YES;
            
            // 将pageview挂在control上
            [control addSubview:pageView];
            
            // 为每个页面添加响应层
            [control addTarget:self action:@selector(pageCliked) forControlEvents:UIControlEventTouchUpInside];
            
            [_scrollView addSubview:control];
            
        }
    }
    return _scrollView;
}
- (UILabel *)lblNumber{
    if (!_lblNumber) {
        _lblNumber = [[UILabel alloc] initWithFrame:CGRectMake((self.width - 40) / 2.0, self.height - 24, 40, 14)];
        _lblNumber.textColor = kColorWithHex(0xffffff);
        _lblNumber.textAlignment = NSTextAlignmentCenter;
        _lblNumber.font = [UIFont systemFontOfSize:10];
        _lblNumber.backgroundColor = kColorWithHex(0x666666);
        _lblNumber.layer.cornerRadius = 7;
        _lblNumber.layer.masksToBounds = YES;
    }
    return _lblNumber;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
